#pragma once
#include <cstdint>
#include <cstdlib>
#include<iostream>
#include <strings.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>


class Sock 
{
private:
    const static int gbacklog=20;
public: 
    int Socket()
    {
        int _serversock=socket(AF_INET, SOCK_DGRAM, 0);
        if(_serversock < 0)
        {
            exit(-1);
        }
        return _serversock;
    }
    void Bind(int sock,uint16_t port,std::string ip)
    {
        struct sockaddr_in server;
        socklen_t len=sizeof(server);
        bzero(&server, sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(port);
        server.sin_addr.s_addr=inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        if(bind(sock, (struct sockaddr*)&server, len) < 0)
        {
            exit(-1);
        }
    }
    void Listen(int sock)
    {
        if(listen(sock, gbacklog) < 0)
        {
            exit(-1);
        }
    }
    //这里是要把来自于客户端的sock接受过来
    int Accept(int sock,uint16_t* port,std::string* ip)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        int serversock=accept(sock, (struct sockaddr*)&client, &len);
        if(serversock < 0)
        {
            return -1;
        }
        if(port){
            *port=ntohs(client.sin_port);
        }
        if(ip){
            *ip=inet_ntoa(client.sin_addr);
        }
    }
    //这里是客户端要与服务端进行连接
    bool Connet(int sock,const uint16_t& server_port,const std::string& server_ip)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        bzero(&client,sizeof(client));
        client.sin_family=AF_INET;
        client.sin_port=htons(server_port);
        client.sin_addr.s_addr=inet_addr(server_ip.c_str());
        if(bind(sock, (struct sockaddr*)&client, len) == 0)
        {
            return true;
        }
        else{
            return false;
        }
    }
    // bool Connet(int sock,const uint16_t& client_port,const std::string& client_ip)
    // {
    //     struct sockaddr_in server;
    //     memset(&server, 0, sizeof(server));
    //     server.sin_family=AF_INET;
    //     server.sin_port=htons(client_port);
    //     server.sin_addr.s_addr=inet_addr(client_ip.c_str());
    // }
};
